package org.x.usermod.controller;

import com.alibaba.fastjson2.JSON;
import com.mybatisflex.core.paginate.Page;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.x.commonmod.config.Result;
import org.x.commonmod.enums.LogAsync;
import org.x.usermod.dto.LogDTO;
import org.x.usermod.dto.LogDetailDTO;
import org.x.usermod.dto.LogQueryParamDTO;
import org.x.usermod.service.LogService;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/api/log")
public class LogController {

    @Autowired
    private LogService logService;

    /**
     * 分页查询日志列表
     * @return 分页结果
     */
    @GetMapping("/list")
    public Result getLogList(LogDTO logDTO) {
        // 调用服务层查询
        Page<LogDTO> result = logService.getLogList(logDTO);

        // 构建响应结果
        return Result.ok(result);
    }
    /**
     * 日志详情查询
     * @return 日志详情
     */
    @GetMapping("/detail")
    public LogDetailDTO getLogDetail(Long id) {
        // 调用服务层查询
        LogDetailDTO result = logService.getLogDetail(id);

        // 构建响应结果
        return result;
    }
    /**
     * 导出所有日志
     * @return 日志数据导出excel文件
     */
    @LogAsync("日志导出")
    @GetMapping("/export")
    public void exportLog(HttpServletResponse response) {
        try {
            // 设置正确的响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=system_logs.xlsx");
            response.setCharacterEncoding("UTF-8");

            // 调用导出服务
            logService.exportLog(response.getOutputStream());
        } catch (Exception e) {
            // 错误处理 - 重置响应并返回JSON错误信息
            response.reset();
            response.setContentType("application/json;charset=UTF-8");
            try {
                // 写入错误信息
                response.getWriter().write(JSON.toJSONString(Result.error("导出失败: " + e.getMessage())));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }


}
